<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class PermissionResource extends JsonResource
{
    /**
     * @var array
     */
    protected $withoutFields = [];

    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return $this->filterFields([
            'id'            => $this->id,
            'name'          => $this->name,
            'display_name'  => $this->display_name,
            'parent_id'     => $this->parent_id,
            'icon'          => $this->icon,
            'sort'          => $this->sort,
            'is_menu'       => $this->is_menu,
            'updated_at'    => $this->updated_at->format('Y-m-d H:i:s'),
        ]);
    }

    public static function collection($resource)
    {
        return tap(new PermissionResourceCollection($resource), function ($collection) {
            $collection->collects = __CLASS__;
        });
    }

    /**
     * 设置需要隐藏过滤掉的键
     *
     * @param array $fields
     * @return $this
     */
    public function hide(array $fields)
    {
        $this->withoutFields = $fields;
        return $this;
    }

    /**
     * 删除隐藏的键
     *
     * @param $array
     * @return array
     */
    protected function filterFields($array)
    {
        return collect($array)->forget($this->withoutFields)->toArray();
    }
}
